<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['lowcode:model:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lowcode:model:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lowcode:model:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模型名称" align="center" prop="modelName" />
      <el-table-column label="数据源" align="center" prop="databaseSourceId">
        <template #default="scope">
          <div v-for="databaseSource in lowcode_database_source" :key="databaseSource.databaseSourceId">
            <p v-if="databaseSource.databaseSourceId == scope.row.databaseSourceId">
              {{ databaseSource.databaseSourceName }}
            </p>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="路由" align="center" prop="url" /> -->
      <el-table-column label="接口对外开放" align="center" prop="exocytosis">
        <template #default="scope">
          <dict-tag :options="lc_field_is" :value="scope.row.exocytosis"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="400">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdateField(scope.row)" v-hasPermi="['lowcode:model:edit']">维护</el-button>
              <el-button link type="primary" icon="Edit" @click="handleDesign(scope.row)" v-hasPermi="['lowcode:model:edit']">设计</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lowcode:model:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lowcode:model:remove']">删除</el-button>
              <el-button link type="primary" icon="Download" @click="handleDownload(scope.row)">下载接口文档</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模型对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="modelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="数据源" prop="databaseSourceId">
            <el-select v-model="form.databaseSourceId" placeholder="请选择">
              <el-option
                v-for="dict in lowcode_database_source"
                :key="dict.databaseSourceId"
                :label="dict.databaseSourceName"
                :value="dict.databaseSourceId"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- <el-form-item label="路由" prop="url">
          <el-input v-model="form.url" placeholder="请输入路由" />
        </el-form-item> -->
        <el-form-item label="接口开放">
          <el-switch 
            v-model="form.exocytosis"
            active-value="1"
            inactive-value="0" />
        </el-form-item>
        <el-space fill style="width: 100%;">
            <el-alert type="info" show-icon :closable="false">
              <p>查询SQL示例：SELECT * FROM lc_test #WHERESQL</p>
            </el-alert>
            <el-form-item label="查询SQL" prop="selectSql">
              <el-input v-model="form.selectSql" type="textarea" placeholder="请输入内容" />
            </el-form-item>
        </el-space>
        <el-space fill style="width: 100%;">
            <el-alert type="info" show-icon :closable="false">
              <p>统计SQL示例：SELECT COUNT(1) AS total FROM lc_test #WHERESQL</p>
            </el-alert>
            <el-form-item label="统计SQL" prop="countSql">
              <el-input v-model="form.countSql" type="textarea" placeholder="请输入内容" />
            </el-form-item>
        </el-space>
        <!-- <el-space fill style="width: 100%;">
            <el-alert type="info" show-icon :closable="false">
              <p>删除SQL示例：DELETE FROM lc_test WHERE id = #WHEREID</p>
            </el-alert>
            <el-form-item label="删除SQL" prop="deleteSql">
              <el-input v-model="form.deleteSql" type="textarea" placeholder="请输入内容" />
            </el-form-item>
        </el-space> -->
        <el-form-item label="新增">
          <el-switch 
            v-model="form.isAdd"
            active-value="1"
            inactive-value="0" />
        </el-form-item>
        <el-form-item label="修改">
          <el-switch 
            v-model="form.isUpdate"
            active-value="1"
            inactive-value="0" />
        </el-form-item>
        <el-form-item label="删除">
          <el-switch 
            v-model="form.isDelete"
            active-value="1"
            inactive-value="0" />
        </el-form-item>
        <el-form-item label="导出">
          <el-switch 
            v-model="form.isExport"
            active-value="1"
            inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改字段弹框 -->
    <el-dialog title="字段维护" v-model="fieldOpen" :fullscreen="true" lock-scroll destroy-on-close append-to-body>
      <Field :modelId="modelId"></Field>
    </el-dialog>

    <!-- 表单设计弹框 -->
    <el-dialog title="表单设计" v-model="designOpen" :fullscreen="true" destroy-on-close append-to-body>
      <div class="dgbg">
        <VFormDesigner ref="vfDesignerRef" :field-list-api="fieldListApi" :global-dsv="globalDsv" @click="saveFormJson">
          <!-- 自定义按钮插槽演示 -->
          <template #customToolButtons>
            <el-button @click="saveFormJson">保存</el-button>
          </template>
        </VFormDesigner>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Model">
import { listModel, getModel, delModel, addModel, updateModel } from "@/api/lowcode/model";
import Field from "../field/index.vue"
import VFormDesigner from '../../../components/form-designer/index.vue'

const { proxy } = getCurrentInstance();
const { lc_field_is } = proxy.useDict(
  "lc_field_is"
);
const { lowcode_database_source } = proxy.useLowcode('lowcode_database_source');

const modelList = ref([]);
const open = ref(false);
const fieldOpen = ref(false);
const designOpen = ref(false)
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const modelId = ref("")
const globalDsv = ref({})
const vfDesignerRef = ref(null)
const modelInfo = ref(null)
const fieldListApi = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelName: undefined,
    selectSql: undefined,
    deleteSql: undefined,
  },
  rules: {
    modelId: [
      { required: true, message: "模型id不能为空", trigger: "blur" }
    ],
    modelName: [
      { required: true, message: "模型名称不能为空", trigger: "blur" }
    ],
    databaseSourceId: [
    { required: true, message: "数据源不能为空", trigger: "change" }
    ],
    selectSql: [
      { required: true, message: "查询sql不能为空", trigger: "blur" }
    ],
    countSql: [
      { required: true, message: "统计sql不能为空", trigger: "blur" }
    ],
    deleteSql: [
      { required: true, message: "删除sql不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询模型列表 */
function getList() {
  loading.value = true;
  listModel(queryParams.value).then(response => {
    modelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    modelId: null,
    modelName: null,
    url: null,
    selectSql: null,
    countSql: null,
    deleteSql: null,
    isAdd: '1',
    isUpdate: '1',
    isDelete: '1',
    isExport: '1',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("modelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.modelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加模型";
}

/** 修改字段按钮操作 */
function handleUpdateField(row){
  modelId.value = row.modelId
  fieldOpen.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _modelId = row.modelId || ids.value
  getModel(_modelId).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改模型";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["modelRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.modelId != null) {
        updateModel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addModel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _modelIds = row.modelId || ids.value;
  proxy.$modal.confirm('是否确认删除模型编号为"' + _modelIds + '"的数据项？').then(function() {
    loading.value = true;
    return delModel(_modelIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 设计 */
function handleDesign(row){

  if(row.modelJson){
    setTimeout(() => {
      vfDesignerRef.value.setFormJson(row.modelJson)
    }, 0);
  }else{
    setTimeout(() => {
      vfDesignerRef.value.setFormJson({
        "widgetList": [],
        "formConfig": {
          "modelName": "formData",
          "refName": "vForm",
          "rulesName": "rules",
          "labelWidth": 80,
          "labelPosition": "left",
          "size": "",
          "labelAlign": "label-left-align",
          "cssCode": "",
          "customClass": [],
          "functions": "",
          "layoutType": "PC",
          "jsonVersion": 3,
          "onFormCreated": "",
          "onFormMounted": "",
          "onFormDataChange": "",
          "onFormValidate": ""
        }
      })
    }, 0);
  }


  fieldListApi.value = {
    URL: import.meta.env.VITE_APP_BASE_API + '/lowcode/model/getFormModelField/' + row.modelId,
    labelKey: 'fieldLabel',
    nameKey: 'fieldName'
  }

  modelInfo.value = row
  designOpen.value = true
}

// 保存表单
function saveFormJson(){
  setTimeout(() => {
    if(modelInfo.value.modelJson == JSON.stringify(vfDesignerRef.value.getFormJson())){
      return
    }
    modelInfo.value.modelJson = JSON.stringify(vfDesignerRef.value.getFormJson())
    updateModel(modelInfo.value).then(response => {
      proxy.$modal.msgSuccess("保存成功");
    });
  }, 0);
}

// 下载接口文档
function handleDownload(row){
  // window.location.href = "http://localhost:8080/lowcode/model/downloadDocument/" + row.modelId;
  proxy.download("/lowcode/model/downloadDocument/" + row.modelId, {
  },`${row.modelName}.doc`);
}

getList();
</script>

<style lang="scss" scoped>

</style>
